import { defineStore } from 'pinia'
import { login as loginApi, getCurrentUser } from '@/api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: (() => {
      try {
        return JSON.parse(localStorage.getItem('user') || 'null')
      } catch (error) {
        console.warn('解析本地用户信息失败', error)
        return null
      }
    })(),
    loading: false,
    error: null
  }),
  getters: {
    isAuthenticated: (state) => Boolean(state.token),
    userId: (state) => state.user?.userId || null,
    userName: (state) => state.user?.userName || ''
  },
  actions: {
    setSession(token, user) {
      this.token = token
      this.user = user
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(user))
    },
    clearSession() {
      this.token = ''
      this.user = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },
    async login(credentials) {
      this.loading = true
      this.error = null
      try {
        const response = await loginApi(credentials)
        const payload = response?.data || {}
        if (!payload.token) {
          throw new Error(response?.message || '登录失败')
        }
        const user = {
          userId: payload.userId,
          userName: payload.userName,
          phone: payload.phone,
          icon: payload.icon,
          preferences: payload.preferences || []
        }
        this.setSession(payload.token, user)
        return user
      } catch (error) {
        this.error = error.message || '登录失败'
        throw error
      } finally {
        this.loading = false
      }
    },
    async fetchCurrentUser() {
      if (!this.token) {
        return null
      }
      try {
        const response = await getCurrentUser()
        const payload = response?.data
        if (payload) {
          const user = {
            userId: payload.userId,
            userName: payload.userName,
            phone: payload.phone,
            icon: payload.icon,
            preferences: payload.preferences || []
          }
          this.setSession(this.token, user)
          return user
        }
        return null
      } catch (error) {
        console.warn('获取当前用户信息失败', error)
        this.clearSession()
        return null
      }
    },
    logout() {
      this.clearSession()
    }
  }
})
